package com.wcy.app.lib.update

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.wcy.app.lib.aop.Permissions
import com.wcy.app.lib.network.HttpUtils
import com.wcy.app.lib.network.interfaces.DownLoadResult
import com.wcy.app.lib.update.interfaces.UpdateInterface
import java.io.File

class UpdateDialog {
    class Builder(private val mContext: AppCompatActivity) {
        private val updatePopurView: UpdatePopurView
        private var mCallBack: UpdateInterface? = null
        fun setContent(uploadBean: VersionBean?): Builder {
            updatePopurView.setContent(uploadBean)
            return this
        }

        fun setUpdateInterface(callBack: UpdateInterface?): Builder {
            mCallBack = callBack
            return this
        }

        fun show() {
            XPopup.Builder(mContext).dismissOnBackPressed(mCallBack == null).dismissOnTouchOutside(false).asCustom(updatePopurView).show()
        }

        private inner class UpdatePopurView(context: Context) : CenterPopupView(context) {
            private var mVersionBean: VersionBean? = null

            /**
             * Apk 文件
             */
            private var mApkFile: File? = null

            /**
             * 当前是否下载中
             */
            private var mDownloading = false

            /**
             * 当前是否下载完毕
             */
            private var mDownloadComplete = false
            lateinit var mProgressView: ProgressBar
            lateinit var mCloseView: TextView
            lateinit var mUpdateView: TextView
            lateinit var viewline: View
            override fun getImplLayoutId(): Int {
                return R.layout.update_dialog
            }

            override fun initPopupContent() {
                super.initPopupContent()
                mCloseView = findViewById(R.id.btn_cancel)
                mUpdateView = findViewById(R.id.btn_commit)
                viewline = findViewById(R.id.view_line)
                mProgressView = findViewById(R.id.pb_update_progress)
                setText(R.id.tv_title, mVersionBean!!.title)
                setText(R.id.tv_version, mVersionBean!!.versionNum)
                setText(R.id.tv_apksize, mVersionBean!!.apkSize)
                setText(R.id.tv_updatecreate, mVersionBean!!.createDate)
                setText(R.id.tv_msg, mVersionBean!!.updateContent)
                if (mVersionBean!!.is_must_update) {
                    mCloseView.isClickable = false
                    viewline.visibility = View.GONE
                    mCloseView.visibility = View.GONE
                }
                mCloseView.setOnClickListener { dismissWith { if (mCallBack != null) mCallBack!!.succeed() } }
                mUpdateView.setOnClickListener {
                    // 判断下载状态
                    if (mDownloadComplete) {
                        if (mApkFile!!.isFile) {
                            // 下载完毕，安装 Apk
                            installApk()
                        } else {
                            // 下载失败，重新下载
                            downloadApk()
                        }
                    } else if (!mDownloading) {
                        // 没有下载，开启下载
                        downloadApk()
                    }
                }
            }

            override fun getMaxWidth(): Int {
                return if (popupInfo.maxWidth == 0) (XPopupUtils.getWindowWidth(context) * 0.9f).toInt() else popupInfo.maxWidth
            }

            fun setContent(uploadBean: VersionBean?) {
                mVersionBean = uploadBean
            }

            private fun setText(id: Int, msg: String) {
                if (!TextUtils.isEmpty(msg)) {
                    val textView = findViewById<TextView>(id)
                    if (TextUtils.isEmpty(textView.text.toString())) textView.text = msg else textView.append(msg)
                    textView.visibility = View.VISIBLE
                    textView.movementMethod = ScrollingMovementMethod.getInstance()
                }
            }

            /**
             * 下载 Apk
             */
            @Permissions(Permission.MANAGE_EXTERNAL_STORAGE)
            private fun downloadApk() {
                // 创建要下载的文件对象
                mApkFile = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), context.getString(R.string.app_name) + "_v" + mVersionBean!!.versionNum + ".apk")
                // 标记为下载中
                mDownloading = true
                // 标记成未下载完成
                mDownloadComplete = false
                // 后台更新
                mCloseView.visibility = View.GONE
                viewline.visibility = View.GONE
                mProgressView.progress = 0
                // 显示进度条
                mProgressView.visibility = View.VISIBLE
                mUpdateView.setText(R.string.update_status_start)
                HttpUtils.downloadFile(null, mVersionBean!!.download_url, mApkFile!!.absolutePath, object : DownLoadResult<String> {
                    override fun onNext(s: String) {
                        mUpdateView.setText(R.string.update_status_successful)
                        // 标记成下载完成
                        mDownloadComplete = true
                        // 标记当前不是下载中
                        mDownloading = false
                        // 安装 Apk
                        installApk()
                    }

                    override fun onError(throwable: Throwable) {
                        // 标记成未下载完成
                        mDownloadComplete = false
                        mDownloading = false
                        mUpdateView.setText(R.string.update_status_failed)
                        // 删除下载的文件
                        mApkFile!!.delete()
                    }

                    override fun Progress(progress: Int, currentSize: Long, totalSize: Long) {
                        mUpdateView.text = String.format(context.getString(R.string.update_status_running), progress)
                        mProgressView.progress = progress
                    }
                })
            }

            /**
             * 安装 Apk
             */
            /**
             * 下载 Apk
             */
            @Permissions(Permission.REQUEST_INSTALL_PACKAGES)
            private fun installApk() {
                val intent = Intent()
                intent.action = Intent.ACTION_VIEW
                val uri: Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(context, context.packageName + ".provider", mApkFile!!)
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                } else {
                    uri = Uri.fromFile(mApkFile)
                }
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            }
        }

        init {
            updatePopurView = UpdatePopurView(mContext)
        }
    }

}